import { React,useState,useRef,useEffect } from 'react';
import './App.css';
import lodash from "lodash"
import {v4 as uuidV4} from "uuid"//v4是里面有的,uuidV4是自定义后续使用的
import dayjs from 'dayjs'
import axios from "axios"

// const list=[
//     { rpid: 'c1', user: { uid: 'u1002', uname: '巡游轨迹', avatar: '/avatar01.png' }, content: '这个视频太棒了！', ctime: '2023-05-01 12:30', likes: 42 },
//     { rpid: 'c2', user: { uid: 'u1003', uname: '肝帝董佳宁', avatar: '/avatar02.png' }, content: '一键三连了', ctime: '2024-05-02 14:15', likes: 115 },
//     { rpid: 'c3', user: { uid: 'u1004', uname: '周杰伦', avatar: '/avatar03.png' }, content: '哎呦不错哦', ctime: '2023-10-21 9:15', likes: 66 }
//   ]



// (模拟)当前登录用户的信息
const currentUser = {
  uid: 'u1002',
  uname: '巡游轨迹',
  avatar: '/avatar01.png'
}

// Tab导航数组:最新、最热
const tabs = [
  {type:'hot',text:'最热'},
  {type:'time',text:'最新'}
]

// 优化二:自定义hook,封装调用数据的函数
function useGetList(){
  // 优化一:注销静态数据list,使用接口调用后台数据
  const [commentList,setCommentList]=useState([])
    // 使用useEffect调用接口获取数据
  useEffect(()=>{
    //请求数据
    async function getList(){
      const res=await axios.get('http://localhost:3004/list')
      console.log(res.data)
      setCommentList(res.data)
    }
    getList()
  },[])
  return {
    setCommentList,
    commentList
  }
}

// 优化三:把每条评论都抽离成单独的UI组件-CommentItem
function CommentItem({item,onDel}){
  return (
    <div key={item.rpid} className="item-item comment">
      <img 
        src={item.user.avatar} 
        alt={item.user.uname} 
        className="avatar"
      />
      <div className="content">
        <div className="header">
          <span className="username">{item.user.uname}</span>
          <span className="time">{item.ctime}</span>
        </div>
        <div className="text">{item.content}</div>
        <div className="actions">
          <span className='like'>▲ {item.likes}</span>
        {/* 判断:如果是当前用户，则显示删除按钮 */}
        {item.user.uid === currentUser.uid && (
          <button onClick={()=>onDel(item.rpid)}>删除</button>
        )}
        </div>
      </div>
    </div>
  )
}

const App = () => {
  const [type,setType]=useState('hot')
  const [inputValue,setInputValue]=useState('')
  const inputRef=useRef(null)

  // 组件内通过解构赋值调用自定义hook的状态和方法
  const {commentList,setCommentList}=useGetList()

  const handleDeleteComment = (id) => {
    console.log(id)//c1
    // 过滤
    setCommentList(commentList.filter(item=>item.rpid!==id))
  }
  const handleTabChange=(item)=>{
    console.log(item.type)
    setType(item.type)
    if(item.type==='hot'){
      // 最热
      const newList=lodash.orderBy(commentList,['likes'],['desc'])
      setCommentList(newList)
    }else{
      // 最新
      const newList=lodash.orderBy(commentList,['ctime'],['desc'])
      setCommentList(newList)
    }

  }

  const handleSubmit=()=>{
    console.log('发布评论')
    // 判断非空
    if(inputValue.trim()==='') return;
    // 发布评论
    const myComment={
      // rpid:`c${commentList.length+1}`,//替换成uuid
      rpid:uuidV4(),//当成一个可执行方法来使用,生成独一无二的id
      user:{...currentUser},
      content:inputValue,
      // ctime:new Date().toLocaleString('zh-CN').split(' ')[0].replace(/\//g, '-'),
      ctime:dayjs(new Date()).format('MM-DD hh:mm'),
      likes:0
    }
    // 提交新评论后:更新状态
    // 1.更新评论列表
    setCommentList([...commentList,myComment])
    // 2.清空input输入框
    setInputValue('')
    // 3.获取DOM元素,文本框重新获得焦点
    inputRef.current.focus();
  }

  // const msg='hello'

  return (
    <div className="comment-section">
      {/* 评论输入区 */}
      <div className="comment-input-area">
        <input 
          type="text"
          placeholder="发个友善的评论吧..."
          value={inputValue}
          onChange={e=>setInputValue(e.target.value)}
          className="comment-input"
          ref={inputRef}
        />
        <button className='submit-btn' onClick={handleSubmit}>发布</button>
      </div>
      
      {/* 导航Tab */}
      <div className="tabs">
      {tabs.map(item=>
         <div 
         key={item.type}
         onClick={()=>handleTabChange(item)}
         className={`nav-item ${type===item.type&&'active'}`}
          >
            {item.text}
        </div>  
    )}
        
      </div>
      
      {/* 评论列表 */}
      <div className="comment-list">
        {commentList.map(item => (
            <CommentItem key={item.rpid} item={item} onDel={handleDeleteComment}/>
        ))}
      </div>
    </div>
  );
};


export default App;
